<#include "componentFieldItem.ftl" />

<template>
    <div class="topic-form">
        <el-form ref="ruleForm" :rules="rules" :model="model" label-width="160px">
            <el-row :gutter="10">
                <#list formBean.fields as item>
                    <@fieldItem item />
                </#list>
                <el-col :span="22">
                    <el-form-item>
                        <el-button @click="handleCancel">取消</el-button>
                        <el-button type="primary" @click="handleSubmit">确定</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script setup>
    import {useData} from "@/utils/useData";
    <#if formBean.componentSet??>
    <#list formBean.componentSet as item>
    <#if item.name =="sc-editor">
    import {defineAsyncComponent} from "vue";
    const scEditor = defineAsyncComponent(() => import('@/components/scEditor/index.vue'));
    <#else>
    import ${item.name} from "${item.model!}";
    </#if>
    </#list>
    </#if>
    import {ref} from "vue";
    <#list formBean.fields as item>
    <#if item.option?length gt 2 >
    const{listData:${item.id}Options}= useData("/${item.option?uncap_first}/list")
    </#if>
    </#list>

    // 定义emit
    const emit = defineEmits(['submit', 'cancel']);

    // 表单数据
    const model = defineModel({
        default: () => ({
            <#list formBean.fields as item>
            ${item.id!}: null <#sep>,
            </#list>
        })
    });

    // 验证规则
    const rules = ref({
        <#list formBean.fields as item>
        <#if item.required>
        ${item.id}: [
            {required: true, message: '请输入${item.title!}', trigger: 'blur'}
            <#if item.type='money'>
            , {type: 'number', message: '${item.title!}必须为数字值'}
            </#if>
        ]<#sep>,
        </#if>
        </#list>
    });

    const ruleForm = ref(null);

    // 处理提交
    const handleSubmit = async () => {
        if (!ruleForm.value) return;

        try {
            await ruleForm.value.validate();
            emit('submit', model.value);
        } catch (error) {
            console.log('表单验证失败', error);
        }
    };

    // 处理取消
    const handleCancel = () => {
        emit('cancel');
    };

    // 暴露表单引用给父组件
    defineExpose({
        ruleForm,
        validate: () => ruleForm.value?.validate(),
        resetFields: () => ruleForm.value?.resetFields()
    });
</script>

<style scoped>
    .topic-form {
        width: 100%;
    }
</style>
